import 'dart:io';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';

import '../../models/upload_task.dart';
import '../../services/upload/upload_service.dart';
import '../../services/preferences_service.dart';

enum UploadFilter {
  all,
  pending,
  uploading,
  completed,
  failed,
  cancelled,
  paused,
}

class UploadController extends GetxController {
  final UploadService _uploadService = Get.find<UploadService>();
  final PreferencesService _preferencesService = Get.find<PreferencesService>();
  
  // 当前显示的上传任务列表
  final RxList<UploadTask> _displayTasks = <UploadTask>[].obs;
  List<UploadTask> get displayTasks => _displayTasks;
  
  // 选中的任务
  final RxList<UploadTask> _selectedTasks = <UploadTask>[].obs;
  List<UploadTask> get selectedTasks => _selectedTasks;
  
  // 当前过滤器
  final Rx<UploadFilter> _currentFilter = UploadFilter.all.obs;
  UploadFilter get currentFilter => _currentFilter.value;
  
  // 搜索关键词
  final RxString _searchKeyword = ''.obs;
  String get searchKeyword => _searchKeyword.value;
  
  // 选择模式
  final RxBool _isSelectionMode = false.obs;
  bool get isSelectionMode => _isSelectionMode.value;
  
  // 自动刷新开关
  final RxBool _autoRefresh = true.obs;
  bool get autoRefresh => _autoRefresh.value;
  
  @override
  void onInit() {
    super.onInit();
    _setupListeners();
    _updateDisplayTasks();
  }
  
  // 设置监听器
  void _setupListeners() {
    // 监听上传任务变化
    ever(_uploadService.uploadTasks.obs, (_) {
      if (_autoRefresh.value) {
        _updateDisplayTasks();
      }
    });
  }
  
  // 更新显示的任务列表
  void _updateDisplayTasks() {
    var tasks = _uploadService.uploadTasks;
    
    // 应用过滤器
    tasks = _applyFilter(tasks);
    
    // 应用搜索
    if (_searchKeyword.value.isNotEmpty) {
      tasks = tasks.where((task) => 
        task.fileName.toLowerCase().contains(_searchKeyword.value.toLowerCase()) ||
        task.targetPath.toLowerCase().contains(_searchKeyword.value.toLowerCase())
      ).toList();
    }
    
    // 按创建时间倒序排列
    tasks.sort((a, b) => b.createdTime.compareTo(a.createdTime));
    
    _displayTasks.value = tasks;
  }
  
  // 应用过滤器
  List<UploadTask> _applyFilter(List<UploadTask> tasks) {
    switch (_currentFilter.value) {
      case UploadFilter.all:
        return tasks;
      case UploadFilter.pending:
        return tasks.where((task) => task.status == UploadStatus.pending).toList();
      case UploadFilter.uploading:
        return tasks.where((task) => task.status == UploadStatus.uploading).toList();
      case UploadFilter.completed:
        return tasks.where((task) => task.status == UploadStatus.completed).toList();
      case UploadFilter.failed:
        return tasks.where((task) => task.status == UploadStatus.failed).toList();
      case UploadFilter.cancelled:
        return tasks.where((task) => task.status == UploadStatus.cancelled).toList();
      case UploadFilter.paused:
        return tasks.where((task) => task.status == UploadStatus.paused).toList();
    }
  }
  
  // 设置过滤器
  void setFilter(UploadFilter filter) {
    _currentFilter.value = filter;
    _updateDisplayTasks();
  }
  
  // 搜索任务
  void searchTasks(String keyword) {
    _searchKeyword.value = keyword;
    _updateDisplayTasks();
  }
  
  // 清除搜索
  void clearSearch() {
    _searchKeyword.value = '';
    _updateDisplayTasks();
  }
  
  // 手动刷新
  void refreshTasks() {
    _updateDisplayTasks();
  }
  
  // 切换自动刷新
  void toggleAutoRefresh() {
    _autoRefresh.value = !_autoRefresh.value;
    if (_autoRefresh.value) {
      _updateDisplayTasks();
    }
  }
  
  // 选择任务
  void selectTask(UploadTask task) {
    if (_selectedTasks.contains(task)) {
      _selectedTasks.remove(task);
    } else {
      _selectedTasks.add(task);
    }
    
    _isSelectionMode.value = _selectedTasks.isNotEmpty;
  }
  
  // 全选当前显示的任务
  void selectAllDisplayed() {
    _selectedTasks.clear();
    _selectedTasks.addAll(_displayTasks);
    _isSelectionMode.value = true;
  }
  
  // 取消选择
  void clearSelection() {
    _selectedTasks.clear();
    _isSelectionMode.value = false;
  }
  
  // 添加上传任务
  Future<void> addUploadTasks() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        allowMultiple: true,
        type: FileType.any,
      );
      
      if (result != null && result.files.isNotEmpty) {
        // 获取目标路径
        final targetPath = await _getTargetPath();
        
        for (final platformFile in result.files) {
          if (platformFile.path != null) {
            final file = File(platformFile.path!);
            await _uploadService.addUploadTask(file, targetPath);
          }
        }
        
        _showSuccess('任务已添加', '${result.files.length} 个文件已添加到上传队列');
        _updateDisplayTasks();
      }
    } catch (e) {
      _showError('添加任务失败', e.toString());
    }
  }
  
  // 获取目标路径
  Future<String> _getTargetPath() async {
    // 这里可以弹出路径选择对话框
    // 暂时返回根目录
    return '/';
  }
  
  // 暂停上传任务
  Future<void> pauseTask(UploadTask task) async {
    try {
      await _uploadService.pauseUpload(task.id);
      _showSuccess('任务已暂停', '${task.fileName} 已暂停上传');
    } catch (e) {
      _showError('暂停失败', e.toString());
    }
  }
  
  // 恢复上传任务
  Future<void> resumeTask(UploadTask task) async {
    try {
      await _uploadService.resumeUpload(task.id);
      _showSuccess('任务已恢复', '${task.fileName} 已恢复上传');
    } catch (e) {
      _showError('恢复失败', e.toString());
    }
  }
  
  // 取消上传任务
  Future<void> cancelTask(UploadTask task) async {
    try {
      await _uploadService.cancelUpload(task.id);
      _showSuccess('任务已取消', '${task.fileName} 已取消上传');
    } catch (e) {
      _showError('取消失败', e.toString());
    }
  }
  
  // 删除上传任务
  Future<void> deleteTask(UploadTask task) async {
    try {
      await _uploadService.deleteUploadTask(task.id);
      _showSuccess('任务已删除', '${task.fileName} 已从列表中删除');
      _updateDisplayTasks();
    } catch (e) {
      _showError('删除失败', e.toString());
    }
  }
  
  // 重试失败的任务
  Future<void> retryTask(UploadTask task) async {
    try {
      await _uploadService.retryFailedTask(task.id);
      _showSuccess('任务已重试', '${task.fileName} 已重新开始上传');
    } catch (e) {
      _showError('重试失败', e.toString());
    }
  }
  
  // 批量暂停
  Future<void> pauseSelectedTasks() async {
    if (_selectedTasks.isEmpty) return;
    
    try {
      for (final task in _selectedTasks) {
        if (task.isUploading) {
          await _uploadService.pauseUpload(task.id);
        }
      }
      
      _showSuccess('批量暂停成功', '${_selectedTasks.length} 个任务已暂停');
      clearSelection();
    } catch (e) {
      _showError('批量暂停失败', e.toString());
    }
  }
  
  // 批量恢复
  Future<void> resumeSelectedTasks() async {
    if (_selectedTasks.isEmpty) return;
    
    try {
      for (final task in _selectedTasks) {
        if (task.isPaused) {
          await _uploadService.resumeUpload(task.id);
        }
      }
      
      _showSuccess('批量恢复成功', '${_selectedTasks.length} 个任务已恢复');
      clearSelection();
    } catch (e) {
      _showError('批量恢复失败', e.toString());
    }
  }
  
  // 批量取消
  Future<void> cancelSelectedTasks() async {
    if (_selectedTasks.isEmpty) return;
    
    try {
      for (final task in _selectedTasks) {
        if (task.isUploading || task.isPending || task.isPaused) {
          await _uploadService.cancelUpload(task.id);
        }
      }
      
      _showSuccess('批量取消成功', '${_selectedTasks.length} 个任务已取消');
      clearSelection();
    } catch (e) {
      _showError('批量取消失败', e.toString());
    }
  }
  
  // 批量删除
  Future<void> deleteSelectedTasks() async {
    if (_selectedTasks.isEmpty) return;
    
    try {
      for (final task in _selectedTasks) {
        await _uploadService.deleteUploadTask(task.id);
      }
      
      _showSuccess('批量删除成功', '${_selectedTasks.length} 个任务已删除');
      clearSelection();
      _updateDisplayTasks();
    } catch (e) {
      _showError('批量删除失败', e.toString());
    }
  }
  
  // 批量重试失败的任务
  Future<void> retryFailedTasks() async {
    final failedTasks = _displayTasks.where((task) => task.isFailed).toList();
    if (failedTasks.isEmpty) {
      _showInfo('没有失败的任务', '当前没有需要重试的任务');
      return;
    }
    
    try {
      for (final task in failedTasks) {
        await _uploadService.retryFailedTask(task.id);
      }
      
      _showSuccess('批量重试成功', '${failedTasks.length} 个失败任务已重试');
    } catch (e) {
      _showError('批量重试失败', e.toString());
    }
  }
  
  // 清除已完成的任务
  Future<void> clearCompletedTasks() async {
    try {
      await _uploadService.clearCompletedTasks();
      _showSuccess('清理完成', '已完成的任务已清理');
      _updateDisplayTasks();
    } catch (e) {
      _showError('清理失败', e.toString());
    }
  }
  
  // 获取任务详情
  Map<String, dynamic> getTaskDetails(UploadTask task) {
    return {
      'id': task.id,
      'fileName': task.fileName,
      'filePath': task.filePath,
      'fileSize': task.fileSize,
      'targetPath': task.targetPath,
      'status': task.status.toString(),
      'progress': task.progress,
      'uploadedBytes': task.uploadedBytes,
      'uploadSpeed': task.uploadSpeed,
      'createdTime': task.createdTime,
      'startTime': task.startTime,
      'completedTime': task.completedTime,
      'errorMessage': task.errorMessage,
      'uploadDuration': task.uploadDuration?.inSeconds,
    };
  }
  
  // 获取上传统计信息
  Map<String, dynamic> getUploadStatistics() {
    final allTasks = _uploadService.uploadTasks;
    final activeTasks = _uploadService.activeUploads;
    
    return {
      'total_tasks': allTasks.length,
      'active_tasks': activeTasks.length,
      'completed_tasks': allTasks.where((t) => t.isCompleted).length,
      'failed_tasks': allTasks.where((t) => t.isFailed).length,
      'pending_tasks': allTasks.where((t) => t.isPending).length,
      'paused_tasks': allTasks.where((t) => t.isPaused).length,
      'cancelled_tasks': allTasks.where((t) => t.isCancelled).length,
      'total_progress': _uploadService.totalProgress,
      'upload_speed': _uploadService.getUploadSpeed(),
      'estimated_time': _uploadService.getEstimatedTimeRemaining()?.inSeconds,
      'displayed_tasks': _displayTasks.length,
      'selected_tasks': _selectedTasks.length,
      'current_filter': _currentFilter.value.toString(),
    };
  }
  
  // 获取过滤器计数
  Map<UploadFilter, int> getFilterCounts() {
    final allTasks = _uploadService.uploadTasks;
    
    return {
      UploadFilter.all: allTasks.length,
      UploadFilter.pending: allTasks.where((t) => t.isPending).length,
      UploadFilter.uploading: allTasks.where((t) => t.isUploading).length,
      UploadFilter.completed: allTasks.where((t) => t.isCompleted).length,
      UploadFilter.failed: allTasks.where((t) => t.isFailed).length,
      UploadFilter.cancelled: allTasks.where((t) => t.isCancelled).length,
      UploadFilter.paused: allTasks.where((t) => t.isPaused).length,
    };
  }
  
  // 显示错误信息
  void _showError(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.red,
      colorText: Colors.white,
      duration: const Duration(seconds: 4),
    );
  }
  
  // 显示成功信息
  void _showSuccess(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.green,
      colorText: Colors.white,
      duration: const Duration(seconds: 3),
    );
  }
  
  // 显示信息
  void _showInfo(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.blue,
      colorText: Colors.white,
      duration: const Duration(seconds: 3),
    );
  }
}